package com.example.springboot.entity;


import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EqualsAndHashCode(callSuper = true)
@Data
public class DiscussionAndUser extends Discussion{
    private String userName;
    private String avatar;
    private String responseUserName;
    private String responseAvatar;

    private List<DiscussionAndUser> children;


    public static <T extends DiscussionAndUser> List<T> buildDiscussionTree(List<T> list) {
        Map<Integer, T> map = new HashMap<Integer, T>(256);
        List<T> trees = new ArrayList<>();
        for (T t:list) {
            map.put(t.getDiscussionId(),t);
        }
        for (T t : list) {
            T parent = map.get(t.getParentId());
            if (parent!=null) {
                List<T> children = (List<T>) parent.getChildren();
                if(children==null){
                    children = new ArrayList<>();
                }
                children.add(t);
                parent.setChildren((List<DiscussionAndUser>) children);
            } else {
                trees.add(t);
            }
        }
        return trees;
    }
}
